/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.nageoffer.shortlink.project.initialize;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import static com.nageoffer.shortlink.project.common.constant.RedisKeyConstant.SHORT_LINK_STATS_STREAM_GROUP_KEY;
import static com.nageoffer.shortlink.project.common.constant.RedisKeyConstant.SHORT_LINK_STATS_STREAM_TOPIC_KEY;
@Component
@RequiredArgsConstructor
public class ShortLinkStatsStreamInitializeTask implements InitializingBean {

    // 注入Redis操作模板，用于执行Stream相关命令
    private final StringRedisTemplate stringRedisTemplate;

    // Spring Bean初始化完成后自动执行的方法
    @Override
    public void afterPropertiesSet() throws Exception {
        // 检查Redis中是否已存在Stream主题键（防止重复初始化）
        Boolean hasKey = stringRedisTemplate.hasKey(SHORT_LINK_STATS_STREAM_TOPIC_KEY);
        // 当Stream不存在时（首次启动或数据被清空），执行初始化
        if (hasKey == null || !hasKey) {
            // 创建Redis Stream和消费者组（参考Redis的XGROUP CREATE命令）
            // 参数说明：
            // SHORT_LINK_STATS_STREAM_TOPIC_KEY - Stream的键名（消息主题）
            // SHORT_LINK_STATS_STREAM_GROUP_KEY - 消费者组名称
            stringRedisTemplate.opsForStream().createGroup(
                SHORT_LINK_STATS_STREAM_TOPIC_KEY, 
                SHORT_LINK_STATS_STREAM_GROUP_KEY
            );
            // 注：此处未指定$或0-0参数，默认从Stream头部开始消费[8](@ref)
        }
        // 若Stream已存在，则跳过初始化（避免覆盖已有消费者组）
    }
}